﻿using System;
using System.IO;
using System.Windows;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Drawing;


namespace SinsMapPacker.Editor
{

class Application
{
    [DllImport("ole32.dll")]
    static extern int CoInitialize(IntPtr pvReserved);

    [STAThread]
    public static void Main(string[] args)
    {
        // Initialize COM
        CoInitialize((System.IntPtr)null);
        // Enable fancy XP styles
        System.Windows.Forms.Application.EnableVisualStyles();

        // Create a main form.
        var mainForm = new MainForm();

        // Check command line arguments
        if (args.Length > 0)
            // Don't run if we can't open the requested file.
            if (!mainForm.OpenMapPack(args[0]))
                return;

        // Go
        System.Windows.Forms.Application.Run(mainForm);
    }
}

static class Util
{
    #region Unmanaged Declarations

    [StructLayout(LayoutKind.Sequential)]
    internal struct SHFILEINFO
    {
        public IntPtr hIcon;
        public IntPtr iIcon;
        public uint dwAttributes;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
        public string szDisplayName;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
        public string szTypeName;
    };

    internal enum SHGFI
    {
        LARGEICON         = 0x00000000,
        SMALLICON         = 0x00000001,
        OPENICON          = 0x00000002,
        SHELLICONSIZE     = 0x00000004,
        PIDL              = 0x00000008,
        USEFILEATTRIBUTES = 0x00000010,        
        DISPLAYNAME       = 0x00000200,
        ICON              = 0x00000100,
        TYPENAME          = 0x00000400,
        ATTRIBUTES        = 0x00000800,
        ICONLOCATION      = 0x00001000,
        EXETYPE           = 0x00002000,
        SYSICONINDEX      = 0x00004000,
        LINKOVERLAY       = 0x00008000,
        SELECTED          = 0x00010000,
        ATTR_SPECIFIED    = 0x00020000,
        //ADDOVERLAYS       = 0,
        //OVERLAYINDEX      = 0,
    }

    internal enum FILE_ATTRIBUTE
    {
        NORMAL = 0x80,
    }

    [DllImport("shell32.dll", CharSet=CharSet.Auto)]
    public static extern IntPtr SHGetFileInfo(
        string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi,
        uint cbFileInfo, uint uFlags);

    #endregion

    public static Icon GetIconForExt(string ext)
    {
        SHFILEINFO shfi = new SHFILEINFO();

        IntPtr hr = SHGetFileInfo(
            ext,
            (uint)FILE_ATTRIBUTE.NORMAL,
            ref shfi,
            (uint)Marshal.SizeOf(shfi),
            (uint)(SHGFI.ICON | SHGFI.SMALLICON | SHGFI.USEFILEATTRIBUTES)
        );

        if (hr == null)
            return null;
        
        return Icon.FromHandle(shfi.hIcon);
    }
}

}